<?php

namespace App\Http\Controllers\Api\Web;

use App\Http\Requests\Api\UserRequest;
use App\Models\User;
use App\Models\Score;
use App\Http\Controllers\Api\Controller;
use App\Http\Resources\Api\UserResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Ixudra\Curl\Facades\Curl;
use PSpell\Config;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{

  //返回用户列表
  public function index()
  {
    //3个用户为一页
    $users = User::paginate(3);
    return UserResource::collection($users);
  }
  //返回单一用户信息
  public function show(User $user)
  {
    return $this->success(new UserResource($user));
  }
  //用户注册
  public function store(UserRequest $request)
  {
    User::create($request->all());
    return $this->setStatusCode(201)->success('用户注册成功');
  }
  //用户登录
  public function login(Request $request)
  {
    // 获取当前守护的名称
    $present_guard = Auth::getDefaultDriver();
    $token = Auth::claims(['guard' => $present_guard])->attempt(['name' => $request->name, 'password' => $request->password]);
    if ($token) {
      return $this->setStatusCode(201)->success(['token' => 'bearer ' . $token]);
    }
    return $this->failed('账号或密码错误', 400);
  }

  //用户退出
  public function logout()
  {
    Auth::logout();
    return $this->success('退出成功...');
  }
  //返回当前登录用户信息
  public function info()
  {
    $user = Auth::user();
    return $this->success(new UserResource($user));
  }

  // 微信小程序授权code获取用户信息及登录
  public function authLogin(Request $request)
  {
    $code = $request->code;
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=%s';
    $result = Curl::to(sprintf($url, env('WECHAT_MINIPROGRAM_APP_ID'), env('WECHAT_MINIPROGRAM_APP_SECRET'), $code, 'authorization_code'))->get();
    // $result = '{"session_key":"p2acAXwV6QwHon9bgSVbkg==","openid":"ooN5J5NfZIq8HKgi9ZQkbwni6G74"}';
    // {"errcode":40163,"errmsg":"code been used, rid: 64802ca9-4846f32d-7c8d2b17"} {"session_key":"p2acAXwV6QwHon9bgSVbkg==","openid":"ooN5J5NfZIq8HKgi9ZQkbwni6G74"}
    $result = json_decode($result, true);
    if (isset($result['errcode'])) {
      return $this->failed($result['errmsg']);
    } else {
      $openid = $result['openid'];
      // 查询openid是否存在
      $userInfo = User::where('wxopenid', $openid)->first();
      $userInfo = $userInfo ? new UserResource($userInfo) : [];
      $present_guard = Auth::getDefaultDriver();
      if ($userInfo && isset($userInfo->id) && $userInfo->id) {
        // 已注册过，直接登录
        $token = Auth::claims(['guard' => $present_guard])->attempt(['name' => $userInfo->name, 'password' => '123456']);
      } else {
        // 注册账号并随机昵称和头像
        $nicknameList = config('random.nickname');
        $avatarList = config('random.avatar');
        $nickname = $nicknameList[array_rand($nicknameList)];
        $avatar = $avatarList[array_rand($avatarList)];
        $name = randomStr(4) . date('YmdHis');
        $password = '123456';
        $users = [
          'nickname' => $nickname,
          'avatar' => $avatar,
          'name' => $name,
          'password' => bcrypt($password),
          'wxopenid' => $openid,
          'score' => 1,
          'pid' => isset($request->pid) && $request->pid ? $request->pid : 0,
          'created_at' => date('Y-m-d H:i:s'),
          'updated_at' => date('Y-m-d H:i:s'),
        ];
        $id = User::insertGetId($users);
        if ($id) {
          $userInfo = User::where('wxopenid', $openid)->first();
          $userInfo = $userInfo ? new UserResource($userInfo) : [];
          // 积分记录
          $scores = [
            'uid' => $userInfo->id,
            'uname' => $userInfo->nickname,
            'uavatar' => $userInfo->avatar,
            'type' => 'register',
            'type_desc' => '注册获取积分',
            'score' => 1,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
          ];
          DB::table('scores')->insert($scores);
          // 邀请者增加积分
          if (isset($request->pid) && $request->pid) {
            DB::table('users')->where('id', $request->pid)->increment('score', 2);
            // 积分记录
            $puserInfo = DB::table('users')->select('id', 'nickname', 'avatar')->where('id', $request->pid)->first();
            if ($puserInfo) {
              $fxscores = [
                'uid' => $request->pid,
                'uname' => $puserInfo->nickname,
                'uavatar' => $puserInfo->avatar,
                'type' => 'invite_register',
                'type_desc' => '邀请好友注册获取积分',
                'score' => 2,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
              ];
              DB::table('scores')->insert($fxscores);
            }
          }
        }
        // 获取登录token
        $token = Auth::claims(['guard' => $present_guard])->attempt(['name' => $name, 'password' => $password]);
      }
      if ($token) {
        return $this->setStatusCode(201)->success(['token' => 'bearer ' . $token, 'userInfo' => $userInfo]);
      }
      return $this->failed('系统错误,请稍后再试');
    }
  }

  // 更新用户基本信息
  public function editUser(Request $request)
  {
    // 获取用户信息
    $present_guard = Auth::getDefaultDriver();
    $userInfo = Auth::claims(['guard' => $present_guard])->user();
    $updateData = [
      'nickname' => $request->nickname ?? $userInfo->nickname,
      'avatar' => $request->avatar ?? $userInfo->avatar,
      'birthday' => $request->birthday ?? $userInfo->birthday,
      'gender' => $request->gender ?? $userInfo->gender,
      'mobile' => $request->mobile ?? $userInfo->mobile,
    ];
    $result = User::where('id', $userInfo->id)->update($updateData);
    if ($result) {
      return $this->success();
    } else {
      return $this->failed('系统错误,请稍后再试');
    }
  }

  // 签到
  public function signIn(Request $request) {
    $present_guard = Auth::getDefaultDriver();
    $userInfo = Auth::claims(['guard' => $present_guard])->user();
    // 查询今天是否签到过
    $request->offsetSet('type', 'sign');
    $scoreInfo = Score::getTodayScoreList($request);
    if($scoreInfo) {
      return $this->failed('今天已签到过，请明天再来');
    }
    DB::beginTransaction();
    DB::table('users')->increment('score');
    $insertData = [
      'uid' => $userInfo->id,
      'uname' => $userInfo->nickname,
      'uavatar' => $userInfo->avatar,
      'type' => 'sign',
      'type_desc' => '签到获取积分',
      'score' => 1,
      'created_at' => date('Y-m-d H:i:s'),
      'updated_at' => date('Y-m-d H:i:s'),
    ];
    DB::table('scores')->insert($insertData);
    DB::commit();
    return $this->success();
  }

  // 我的收藏、点赞
  public function myLoveAndCollect(Request $request) {
    $present_guard = Auth::getDefaultDriver();
    $userInfo = Auth::claims(['guard' => $present_guard])->user();
    $list = DB::table($request->type)->where('uid', $userInfo->id)->where('status', 1)->paginate($request->size);
    return $this->success($list);
  } 

  // 积分记录
  public function scoreRecord(Request $request) {
    $present_guard = Auth::getDefaultDriver();
    $userInfo = Auth::claims(['guard' => $present_guard])->user();
    $list = DB::table('scores')->where('uid', $userInfo->id)->orderBy('created_at', 'DESC')->paginate($request->size);
    return $this->success($list);
  }

  // 我的邀请
  public function myInvite(Request $request) {
    $present_guard = Auth::getDefaultDriver();
    $userInfo = Auth::claims(['guard' => $present_guard])->user();
    $inviteList = DB::table('users')->where('pid', $userInfo->id)->get();
    return $this->success($inviteList);
  }
}
